package walletuserslogic

import (
	"context"
	"github.com/shopspring/decimal"
	"go.uber.org/zap"
	"navi-mumbai/app/rpc/model/pg/wallet"
	"navi-mumbai/app/rpc/wallet/internal/svc"
	"navi-mumbai/app/rpc/wallet/pb"
	"navi-mumbai/common/key/dbkey"
	"navi-mumbai/common/key/walletkey"
	"navi-mumbai/common/utils"
	"navi-mumbai/common/xerr"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateGameWalletBalanceLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateGameWalletBalanceLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateGameWalletBalanceLogic {
	return &UpdateGameWalletBalanceLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 更新游戏端钱包余额
func (l *UpdateGameWalletBalanceLogic) UpdateGameWalletBalance(in *pb.UpdateGameWalletBalanceReq) (*pb.UpdateGameWalletBalanceResp, error) {
	defer utils.RecoverPanic()

	var dMoneyAmount decimal.Decimal
	dMoneyAmount, err := decimal.NewFromString(in.MoneyAmount)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, err.Error())
	}
	iMoneyAmount := dMoneyAmount.Mul(decimal.NewFromInt(walletkey.MoneyScale)).RoundFloor(0).IntPart()
	ugw, err := l.svcCtx.UserGameWalletModel.FindOneByUidProviderIdMoneyType(l.ctx, in.Uid, in.ProviderId, in.MoneyType)
	if err != nil && err != wallet.ErrNotFound {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
	}

	if ugw == nil { // 不存在则创建
		ugw = &wallet.UserGameWallet{
			Uid:         in.Uid,
			MoneyType:   in.MoneyType,
			MoneyAmount: iMoneyAmount,
			State:       dbkey.Enable,
			ProviderId:  in.ProviderId,
		}

		_, err = l.svcCtx.UserGameWalletModel.Insert(l.ctx, ugw)
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
		}
	} else {
		err = l.svcCtx.UserGameWalletModel.UpdateMoneyAmount(l.ctx, ugw.Id, ugw.Uid, ugw.ProviderId, ugw.MoneyType, iMoneyAmount)
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
		}
	}
	return &pb.UpdateGameWalletBalanceResp{}, nil
}
